<?php

namespace app\admin\model\yalimedia\course;

use think\Model;

class Unit extends Model
{
    // 表名
    protected $name = 'yalimedia_course_unit';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [

    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $model = new self();
            $count = $model->where(['course_id'=>$row['course_id']])->count();

            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => ($count)]);
        });
    }

    public static function sort($course_id,$unit_id,$old_weigh,$new_weigh){

        $unitModel = new Unit();
        $total = $unitModel->where(['course_id'=>$course_id])->count();
        if($new_weigh<=0){
            $new_weigh = 1;
        }else if($new_weigh >= $total){
            $new_weigh = $total;
        }

        $unitModel = new Unit();
        $unitModel->where(['course_id'=>$course_id,'weigh'=>$new_weigh])->update(['weigh'=>$old_weigh]);

        $unitModel = new Unit();
        $unitModel->where(['course_id'=>$course_id,'id'=>$unit_id])->update(['weigh'=>$new_weigh]);

    }








}
